const bookModel = require("../module/book");
const puppeteer = require("puppeteer");

const getAllBook = async ctx => {
    let url = "https://www.dushu.com/lianzai/1126.html"
    let model = bookModel

    let info = {
        name:"",
        author:"",
        desc:"",
        authorDesc:"",
        press:"",
        coverImg:"",
        time:""
    }
    let chapter = []

    let browser = await puppeteer.launch({headless:true})
    let page = await browser.newPage()
    page.setJavaScriptEnabled(true)
    page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36")

    //去到一个子分类中
    await page.goto(url)

    //获取每一本书详情的链接
    let links = await page.evaluate(() => {
        let bookHref = document.querySelectorAll("div.bookslist > ul > li > div > h3 > a")
        let HrefArr = []
        for(let i=0;i<bookHref.length;i++){
            HrefArr.push(bookHref[i].href)
        }
        return HrefArr
    })
    await sleep(1000)
    //挨个去到每一本书的详情页
    for(let j=0;j<links.length;j++){
        info = {}
        chapter = []
        await page.goto(links[j])
        //获取所有info
        info.name = await page.$$eval("body > div:nth-child(6) > div.bookdetails-left > div.book-title > h1",(item) => item.map(item => item.innerText))
        info.author = await page.$$eval("body > div:nth-child(6) > div.bookdetails-left > div.book-details > div.book-details-left > table > tbody > tr:nth-child(1) > td:nth-child(2)",(item) => item.map(item => item.innerText))
        info.desc = await page.$$eval("body > div:nth-child(6) > div.bookdetails-left > div:nth-child(4) > div > div",(item) => item.map(item => item.innerText))
        info.authorDesc = await page.$$eval("body > div:nth-child(6) > div.bookdetails-left > div:nth-child(5) > div > div",(item) => item.map(item => item.innerText))
        info.press = await page.$$eval("tr:nth-child(2) > td:nth-child(2) > a",(item) => item.map(item => item.innerText))
        info.coverImg = await page.$$eval("div.book-pic > div.pic > img",(item) => item.map(item => item.innerText))
        //获取所有章节链接
        let allChapterLinks = await page.evaluate(() => {
            let allLinks = document.querySelectorAll("#ctl00_c1_volumes_ctl00_chapters > tbody > tr > td > a")
            let chapter = []
            for(let j=0;j<allLinks.length;j++){
                let obj = {}
                obj.title = allLinks[j].innerText
                obj.url = allLinks[j].href
                chapter.push(obj)
            }
            return chapter
        })
        for(let m=0;m<allChapterLinks.length;m++){
            let totalObj = {}
            await page.goto(allChapterLinks[m].url)
            await page.waitForSelector("div.content_txt")
            let content = await page.$$eval("div.content_txt",(links) => links.map((x) => x.innerHTML))
            totalObj.title = allChapterLinks[m].title
            totalObj.num = m + 1
            totalObj.content = content
            chapter.push(totalObj)
        }
        // await model.create({info:info,chapter:chapter})
        //     .then(res => {
        //         if(res){
        //             ctx.body = {
        //                 code:200,
        //                 msg:`${info.name}插入成功`
        //             }
        //         }
        //     })
        //     .catch(err => {
        //         ctx.body = {
        //             code:500,
        //             msg:`${info.name}插入失败`
        //         }
        //     })
        // await sleep(2000)
        if(j == 0){
            break;
        }
    }
    async function getContentByClass(d){
        let finallyContent = ""
        await page.evaluate((d) => {
            let content = document.querySelector(d)[0]
            finallyContent = content.innerText
        },d)
        return finallyContent
    }

    function sleep(delay) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                try {
                    resolve(1)
                } catch (e) {
                    reject(0)
                }
            }, delay)
        })
    }

    ctx.body = {
        code:200,
        msg:"请求成功",
        books:{
            info:info,
            chapter:chapter
        }
    }

}

module.exports = {
    getAllBook
}